/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: server.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月12日 星期一 16时19分12秒
***************************************************/
//基于udp协议开发一个简易聊天工具，客户端和服务器聊
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
int main(int argc,const char* argv[])
{
	int sock = 0;
	int ret = 0;
	char buf[1024] = {0};
	char dest[1024] = {0};

	struct sockaddr_in addr;
        memset(&addr,0,sizeof(addr));

	sock = socket(AF_INET,SOCK_DGRAM,0);
	if(sock == -1)
	{
		perror("sock");
		exit(-1);
	}

	addr.sin_family = AF_INET;
        addr.sin_port = htons(6666);
        addr.sin_addr.s_addr = inet_addr("192.168.198.128");

	ret = bind(sock,(struct sockaddr *)&addr,sizeof(struct sockaddr));
	if(ret == -1)
	{
		perror("bind");
		exit(-1);
	}

	struct sockaddr_in cliaddr;
	memset(&cliaddr,0,sizeof(cliaddr));

	int len = sizeof(struct sockaddr);

	time_t rawtime; 
	struct tm * timeinfo;
	while(1)
	{
		ret = recvfrom(sock,buf,1024,0,(struct sockaddr *)&cliaddr,&len);
		if(ret == -1)
		{
			perror("recvfrom");
			exit(-1);
		}
		if(strcmp(buf,"exit") == 0){
			break;
		}
		printf("buf is %s\n",buf);
		printf("ip is %s\n",inet_ntoa(cliaddr.sin_addr));
		printf("port is %d\n",cliaddr.sin_port);
	

		
		printf("请输入信息:\n");
		scanf("%s",dest);
		if(strcmp(dest,"exit") == 0){
			ret = sendto(sock,dest,strlen(dest),0,(struct sockaddr *)&cliaddr,sizeof(struct sockaddr));
			if(ret == -1)
			{
				perror("sendto");
				exit(-1);
			}
			break;
		}
		ret = sendto(sock,dest,strlen(dest),0,(struct sockaddr *)&cliaddr,sizeof(struct sockaddr));
		if(ret == -1)
		{
			perror("sendto");
			exit(-1);
		}

	}

	close(sock);


    return 0;
}
